package com.bop.dehong.center;

import java.math.BigDecimal;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.base.dehong.http.RequestCallBack;
import com.base.dehong.util.PreferencesUtils;
import com.base.dehong.util.StringUtils;
import com.base.dehong.util.ToastUtils;
import com.bop.dehong.R;
import com.bop.dehong.base.BaseFragment;
import com.bop.dehong.base.DeHongApp;
import com.bop.dehong.bid.MyBidActivity;
import com.bop.dehong.center.transaction.TransactionActivity;
import com.bop.dehong.config.Config;
import com.bop.dehong.decaifu.ToubiaoTyjActivity;
import com.bop.dehong.http.model.GetUserInfoModel;
import com.bop.dehong.huodong.HuodongAct;
import com.bop.dehong.info.TiyanjinInfo;
import com.bop.dehong.info.UserInfo;
import com.bop.dehong.loan.MyLoanActivity;
import com.bop.dehong.main.MainActivity;
import com.bop.dehong.more.MoreActivity;
import com.bop.dehong.setting.BankCardActivity;
import com.bop.dehong.setting.NameAuthActivity;
import com.bop.dehong.setting.PersonalSettingActivity;
import com.bop.dehong.util.SharePopUtil;
import com.bop.dehong.webview.WebViewActivity;
import com.bop.dehong.widget.CircleImageView;
import com.nostra13.universalimageloader.core.ImageLoader;

/**
 * 个人中心
 * @author TangWenhan/YeFengyun
 */
public class PersonalCenterActivity extends BaseFragment {
	private MainActivity mActivity;
	private RelativeLayout mBtnUser;
	private LinearLayout tyjLayout;
	private TextView mUsername;
	private ImageView mLevel, iv_title, tyjIv;
	private TextView mIntegral, mBalance, devideTv, tyjTv, tyjsyTv, tyjjeTv;
	private Button rzBtn;
	private CircleImageView mHeadView;
	private TextView mTotalMoneyTv,mAvailableFundsTv,mInterestTv;
	private TextView mTransactionTv;
	private GetUserInfoModel mGetInfoModel;
	private int mCertification = 0;
	private String id;
	private String uid;
	private int emoney;
	private Long local;
	private final int  RESULT_FOR_SETTING = 101;
	private final int  RESULT_FOR_NAMEAUTH = 103;
	private final int  RESULT_FOR_WITHDRAW = 104;
	private final int  RESULT_FOR_RECHARGE = 105;
	private final int  RESULT_FOR_BINDCARD = 106;
	private String availablefund;
	
	@Override
	protected void initTop() {
		mPageName = getClass().getName();
		iv_title = getView(R.id.iv_right);
		registerViewClickListener(iv_title);
		iv_title.setImageResource(R.drawable.btn_more);
	}



	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		mActivity = (MainActivity) activity;
	}
	
	
	@Override
	public void initData() {
		reqInfo();//切换标签回来时刷新
	}
	
	private void reqInfo(){
		showProgressDialog();
		if (mGetInfoModel == null) {
			mGetInfoModel = new GetUserInfoModel(getActivity(), getCallback);
		}
		local = System.currentTimeMillis() / 1000;
		if (DeHongApp.mLoginEntity != null) {
			uid = DeHongApp.mLoginEntity.uid;
			mGetInfoModel.doNet(uid);
		}
	}

	public void initData(UserInfo info){
		if (TextUtils.isEmpty(info.head)) {
			mHeadView.setImageResource(R.drawable.ico_default_avatar);
		}else{
			ImageLoader.getInstance().displayImage(info.head, mHeadView);
		}
		mCertification = Integer.valueOf(info.certification);
		if (mCertification == 0) {
			rzBtn.setVisibility(View.VISIBLE);
		}else if (mCertification == 1) {
			rzBtn.setVisibility(View.VISIBLE);
			rzBtn.setText("实名认证中");
		}else {
			rzBtn.setVisibility(View.GONE);
		}
		String username = "";
		if (!TextUtils.isEmpty(info.nickname)) {
			username = info.nickname;
		}else{
			if (mCertification == 2){
				username = info.name;
			}else
			if (!TextUtils.isEmpty(info.cellphone)) {
//				username = info.cellphone;
				username = PreferencesUtils.getString(getActivity(), Config.USERNAME);
			}
		}
		mUsername.setText(username);
		String totalmoney = info.total_money;
		if (Double.valueOf(totalmoney) == 0.0) {//处理返回0.00的千分符
			totalmoney = "0.00";
			mTotalMoneyTv.setText(totalmoney);
		}else {
			mTotalMoneyTv.setText(StringUtils.getThousandFormatValue(totalmoney));
		}
		availablefund = info.available_funds;
		if (Double.valueOf(availablefund) == 0.0) {
			availablefund = "0.00";
			mAvailableFundsTv.setText(availablefund);
		}else {
			mAvailableFundsTv.setText(StringUtils.getThousandFormatValue(availablefund));
		}
		String interest = info.interest;
		if (Double.valueOf(availablefund) == 0.0){
			interest = "0.00";
			mInterestTv.setText(interest);
		}else {
			mInterestTv.setText(StringUtils.getThousandFormatValue(interest));
		}
		TiyanjinInfo tyjInfo = info.emoney;
		if (tyjInfo != null) {
			tyjLayout.setVisibility(View.VISIBLE);
			
			if (!TextUtils.isEmpty(tyjInfo.emoney)) {
				emoney = Integer.valueOf(tyjInfo.emoney);
				if (emoney > 0) {//根据emoney是否大于0判断是否隐藏体验金布局
					devideTv.setVisibility(View.VISIBLE);
					tyjIv.setVisibility(View.VISIBLE);
					tyjjeTv.setText("+" + StringUtils.getThousandFormatValue(tyjInfo.emoney) + "元体验金");
					id = tyjInfo.bid;
				}
			}
			if (!TextUtils.isEmpty(tyjInfo.stayin)) {
				Float stayin = Float.valueOf(tyjInfo.stayin);
				if (stayin > 0.0f) {//根据stayin判断是否有“待收体验金收益”
					devideTv.setVisibility(View.VISIBLE);
					tyjTv.setText("待收体验金收益（元）");
					tyjsyTv.setText(StringUtils.getThousandFormatValue(tyjInfo.stayin));
				}
			}
		}
	}
	
	RequestCallBack<UserInfo> getCallback = new RequestCallBack<UserInfo>() {

		@Override
		public void end() {
			disappearProgressDialog();
		}

		@Override
		public void onSuccess(UserInfo info) {
			super.onSuccess(info);
			Long net = info.stamp;
			Long modify = net - local;
			if (Math.abs(modify) >= 300) {
				PreferencesUtils.putLong(mActivity, Config.TAG, modify);	
			}
			DeHongApp.mUserInfo = info;
			initData(DeHongApp.mUserInfo);
		}
		
	};
	
	@Override
	protected void initUI() {
		mTransactionTv = getView(R.id.transaction);
		tyjLayout = getView(R.id.tyj_layout);
		devideTv = getView(R.id.devide_line);
		tyjTv = getView(R.id.tyj_tv);
		tyjsyTv = getView(R.id.tyjsy_tv);
		tyjIv = getView(R.id.tyj_iv);
		tyjjeTv = getView(R.id.tiyanjin);
		rzBtn = getView(R.id.btn_rz);
		mHeadView = getView(R.id.personal_center_user_icon);
		mUsername = getView(R.id.name);
		mTotalMoneyTv = getView(R.id.total_money);
		mAvailableFundsTv = getView(R.id.available_funds);
		mInterestTv = getView(R.id.interest);
		registerViewClickListener(mTransactionTv,
				getView(R.id.withdrawals),
				getView(R.id.loan),
				getView(R.id.bid),
				getView(R.id.recharge),
				mHeadView,
				getView(R.id.safety),
				rzBtn,
				getView(R.id.huodong),
				getView(R.id.tv_share),
				getView(R.id.dehong_coin), tyjLayout);
	}	
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode != Activity.RESULT_OK) {
			return;
		}
		if (requestCode == RESULT_FOR_SETTING) {
			removeHeadCache();
			reqInfo();
		}else if (requestCode == RESULT_FOR_NAMEAUTH) {
//			initData(DeHongApp.mUserInfo);
			reqInfo();
		}else if (requestCode == RESULT_FOR_WITHDRAW) {
			reqInfo();
		}else if (requestCode == RESULT_FOR_RECHARGE) {
			reqInfo();
		}else if (requestCode == RESULT_FOR_BINDCARD) {
			reqInfo();
		}
		 
	}

	@Override
	protected int getContentViewId() {
		return R.layout.activity_personal_center;
	}

	@Override
	public void onClick(View v)
	{
		switch (v.getId()) {
		case R.id.tyj_layout:
			if (!TextUtils.isEmpty(id)) {
//				Intent goTYJ = new Intent(getActivity(), ToubiaoTyjActivity.class);
				Bundle bundle = new Bundle();
				bundle.putString(Config.CAT_ID, id + "");
				bundle.putInt(Config.CODE, emoney);
				openActivity(ToubiaoTyjActivity.class, bundle);
			}
			break;
		case R.id.iv_right:
			openActivity(MoreActivity.class);
			break;
		case R.id.transaction:
			openActivity(TransactionActivity.class);
//			openActivity(TransactionRecordsActivity.class);
			break;
		case R.id.withdrawals:
			if (DeHongApp.mUserInfo != null ) {
				if (mCertification == 2) {
					if (Integer.valueOf(DeHongApp.mUserInfo.bank_audit) == 2) {
						Double money = 0.0;
						String moneyStr = "";
						moneyStr = availablefund;//避免传递带千分符的金额数值到提现页
//						moneyStr = getStr4TextView(mAvailableFundsTv);
//						moneyStr = getStr4TextView(mTotalMoneyTv);
						if (!TextUtils.isEmpty(moneyStr)) {
							BigDecimal m= new BigDecimal(moneyStr);
							money = m.doubleValue();
						}
						Intent intent = new Intent(getActivity(),WithdrawalsActivity.class);//提现
						intent.putExtra("money", money);
						startActivityForResult(intent, RESULT_FOR_WITHDRAW);
					}else{
						ToastUtils.showLong(getActivity(), "您还没有绑定银行卡，请绑卡后提现！");
						Intent intent3 = new Intent(getActivity(), BankCardActivity.class);
						intent3.putExtra(Config.UID, uid);
						startActivityForResult(intent3, RESULT_FOR_BINDCARD);
					}
				}else{
					ToastUtils.showLong(getActivity(), "您还没有实名认证，请认证后提现！");
					Intent intent3 = new Intent(getActivity(), NameAuthActivity.class);
					intent3.putExtra(Config.UID, uid);
					startActivityForResult(intent3, RESULT_FOR_NAMEAUTH);
				}
			}else {
				ToastUtils.show(getActivity(), "你还未登录！");
			}
			break;
		case R.id.loan:
			openActivity(MyLoanActivity.class);
			break;
		case R.id.bid:
			openActivity(MyBidActivity.class);
			break;
		case R.id.recharge:
				if (mCertification == 2) {
					Intent reIntent = new Intent(getActivity(),RechargeActivity.class);//充值
					startActivityForResult(reIntent, RESULT_FOR_RECHARGE);
				}else{
					ToastUtils.showLong(getActivity(), "您还没有实名认证，请认证后充值!");
					Intent intent3 = new Intent(getActivity(), NameAuthActivity.class);
					intent3.putExtra(Config.UID, uid);
					startActivityForResult(intent3, RESULT_FOR_NAMEAUTH);
				}
			break;
		case R.id.personal_center_user_icon:
			Intent settingIntent = new Intent(getActivity(),PersonalSettingActivity.class);
			settingIntent.putExtra(Config.UID, uid);
			startActivityForResult(settingIntent, RESULT_FOR_SETTING);
			break;
		case R.id.safety:
			Intent intent = new Intent(getActivity(),WebViewActivity.class);
			intent.putExtra("title", "安全保障");
			intent.putExtra("url", Config.getIP() + Config.security);
			intent.putExtra(Config.GO_BACK, true);
			startActivity(intent);
			break;
		case R.id.dehong_coin:
			Intent intent3 = new Intent(getActivity(), WebViewActivity.class);
			intent3.putExtra("title", "体验金");
			intent3.putExtra("url", Config.getIP() + Config.dehongcion);
			startActivity(intent3);
			break;
		case R.id.btn_rz:
			Intent intent2  = new Intent(getActivity(), NameAuthActivity.class);
			intent2.putExtra(Config.UID, uid);
			startActivityForResult(intent2, RESULT_FOR_NAMEAUTH);
			break;
		case R.id.huodong:
			openActivity(HuodongAct.class);
//			openActivity(HuodongActivity.class);
			break;
		case R.id.tv_share:
			SharePopUtil sharePopUtil = new SharePopUtil(getActivity(), v);
			sharePopUtil.setShareParams(Config.SHARE_TITLE,
					 Config.SHARE_IMG,
					Config.SHARE_CONTENT, Config.SHARE_URL, SharePopUtil.shareNetImg);
			break;
		default:
			break;
		}
	}



	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id)
	{
		// TODO Auto-generated method stub
		
	}
	
	@SuppressWarnings("deprecation")
	private void removeHeadCache(){
		if (! TextUtils.isEmpty(DeHongApp.mLoginEntity.head)) {
			ImageLoader.getInstance().getMemoryCache().clear();
			ImageLoader.getInstance().getDiskCache().remove(DeHongApp.mLoginEntity.head);
		}
	}
}
